# 连接mongo数据库
import pymongo

# python的时区库
import pytz

import json

# 设置时区
tzinfo = pytz.timezone('Asia/Shanghai')


# 连接mongo的数据库 类

class MyMongo:

    def __init__(self):
        # 数据库连接
        self.client = pymongo.MongoClient(host='localhost', port=27017, tz_aware=True, tzinfo=tzinfo)
        self.docker_mongo = pymongo.MongoClient(host='192.168.99.100', port=27018, tz_aware=True, tzinfo=tzinfo)

        # 声明数据库
        self.db = self.client.mytornado
        self.dbs = self.docker_mongo.mytornado

        self.table = self.db.send
        self.tables = self.dbs.send

    # 删除数据
    def remove(self, data):
        return self.table.delete_one(data)

    # 插入数据
    def insert(self, data):

        res = hash(data['id'] % 2)

        print(data['id'])

        send = self.find_one({'id': data['id']})

        if res == 0:
            if not send:
                self.table.insert_one({"id": data['id'], "send": []})
            send = self.find_one({'id': data['id']})
            x = send['send'].append(data)
            self.table.update({"uid": data['id']}, 'send', x)

        else:
            if not send:
                self.tables.insert_one({"id": data['id'], "send": []})
            send = self.find_one({'id': data['id']})
            list1 = send['send'].append(data)
            self.tables.update({'id': data['id']}, 'send', list1)

    # 查询单个数据
    def find_one(self, data):

        res = self.table.find_one(data)

        return res

    # 查询多个数据
    def find(self, data):

        res = self.table.find(data)
        list1 = []
        for i in res:
            list1.append(i)

        return list1

    # 修改数据
    def update(self, find, field, data):
        # 先查询
        mydata = self.table.find_one(find)
        # 指定字段
        mydata[field] = data
        # 修改
        res = self.table.update_one(find, {'$set': mydata})
        return res


mongo = MyMongo()
mongo.insert({'id': 4, 'send': {'send': '你海鸥'}})
# res = mongo.find_one({'id': 1})

# if res:
#     print(res['send'])
#     list1 = res['send']
#     list1.append({'xxx': '年后'})
#     print(list1)
# mongo.update({'id':1},'send',list1)
# for i in res:
#     print(i)
# print(res)
